package cn.tsmchina.one.controller.order;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tsmchina.one.domain.order.Order;
import cn.tsmchina.one.domain.user.Customer;
import cn.tsmchina.one.domain.user.User;
import cn.tsmchina.one.service.category.CategoryService;
import cn.tsmchina.one.service.order.OrderService;
import cn.tsmchina.one.service.user.CustomerService;
import cn.tsmchina.one.util.C;
import cn.tsmchina.one.util.LoginUtil;

@Controller
@RequestMapping("/order")
public class OrderController
{
	@Autowired
	private OrderService orderService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private CategoryService categoryService;
	
	
	//时间仓促  暂时这么做。
	@RequestMapping(value="/pull",method=RequestMethod.POST)
	@ResponseBody
	public Object flag(@RequestParam int totalNum, HttpServletRequest request) {
		request.getSession().getAttribute("cid");
		Map<String, Object> data = new HashMap<>();
		Customer c = (Customer)request.getSession().getAttribute("customer");//登录时已加入session
		String cname = c.getName();
		Integer type = c.getType();
		int newNum = totalNum;
		
		//如果是超级管理员，则所有消息都推送,包括红客会
		if(type!=null && type.equals(1)){
			newNum = orderService.getTotalNum();
		}else {
			//如果是店铺管理员，则只推送当前customerId下的
			List<Order> l = orderService.getOrdersByName(cname);
			newNum = l.size();
		}
		if(newNum > 0 && totalNum == 0){
			//第一次轮询时将进这里，不推送
			data.put("totalNum", newNum);
			data.put("flag", false);
			return data;
		}
		if(newNum > totalNum){
			data.put("totalNum", newNum);
			data.put("flag", true);
			return data;
		}
		
		data.put("totalNum", newNum);
		data.put("flag", false);
		return data;
	}
	
	/**
	 * 查询订单信息
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/query")
	public String queryOrder(HttpServletRequest request)
	{
		int page = 1;
		try
		{
			String pageIndex = request.getParameter("page");
			if(pageIndex != null)
				if(!StringUtils.isEmpty(page))
					page = Integer.parseInt(pageIndex);
			
			Map<String, String[]> map = request.getParameterMap();
			Map<String, String> parameter = new HashMap<>();
			for (Entry<String, String[]> en : map.entrySet())
			{
				parameter.put(en.getKey(), en.getValue()[0]);
			}
			//如果当前请求不是管理员，那么只显示当前店铺的订单，否则按照搜索条件显示
			Integer type = LoginUtil.getCustomerType(request);
			//如果是null 则一定不是管理员
			if(null == type || type.intValue() != 1)
			{
				//获取当前店铺的名字
				Integer lid = LoginUtil.getLoginId(request, customerService);
				String name = categoryService.getNameByLoginId(lid);
				//将搜索条件的店铺名字设置为当前店铺
				parameter.put("toAddress", name);
			}
		

			long cid = LoginUtil.getCustomerId(request, customerService);
			List<Order> list = orderService.getQueryOrders(parameter,page, cid); 
			int total = orderService.getTotal(parameter,cid);
			//int total = list.size();
			int pageTotal = total % C.Paging.SIZE == 0 ? total / C.Paging.SIZE : total / C.Paging.SIZE + 1;
			request.setAttribute("orders", list);
			request.setAttribute("len",list.size());
			request.setAttribute("page",page);
			request.setAttribute("pageTotal", pageTotal);
			request.setAttribute("total", total);
			
			request.setAttribute("categories", categoryService.getAllSubRestaurant(cid));
		} catch (Exception e)
		{
			e.printStackTrace();
			request.setAttribute("len",0);
		}
		return "order/queryOrder";
	}
	
	@RequestMapping("/send")
	@ResponseBody
	public Object sendProduct(long orderId,String status)
	{
		Map<String, Object> data = new HashMap<>();
		try
		{
			if(status.equals("go"))
			{
				//配送中
				orderService.updateSendStatus(orderId,C.SendStatus.go);
			}
			else if(status.equals("yes"))
			{
				//已送达
				orderService.updateSendStatus(orderId,C.SendStatus.yes);
				//更新支付状态
				orderService.updatePayStatus(orderId);
			}
			data.put("ok", true);
		} catch (Exception e)
		{
			e.printStackTrace();
			data.put("ok", false);
			data.put("msg", "出错了,请稍后再试!");
		}
		return data;
	}
	
	@RequestMapping("/info")
	public String orderInfo(double totalPrice, int credits, int pcount, HttpServletRequest request)
	{
		User user = (User) request.getSession().getAttribute("user");
		if(user!=null) {
			request.setAttribute("user", user);
			//TODO根据积分兑换规则计算出新的价格
			request.setAttribute("totalPrice", totalPrice);
			request.setAttribute("pcount", pcount);
		}
		return "m/orderInfo";
	}
}
